package org.codehaus.activemq.service.impl;

import EDU.oswego.cs.dl.util.concurrent.ConcurrentHashMap;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import javax.jms.JMSException;
import org.codehaus.activemq.DuplicateDurableSubscriptionException;
import org.codehaus.activemq.broker.BrokerClient;
import org.codehaus.activemq.filter.Filter;
import org.codehaus.activemq.message.ConsumerInfo;
import org.codehaus.activemq.service.Dispatcher;
import org.codehaus.activemq.service.Subscription;
import org.codehaus.activemq.service.SubscriptionContainer;

public class SubscriptionContainerImpl
  implements SubscriptionContainer
{
  private Map subscriptions;

  public SubscriptionContainerImpl()
  {
    this(new ConcurrentHashMap());
  }

  public SubscriptionContainerImpl(Map subscriptions) {
    this.subscriptions = subscriptions;
  }

  public String toString() {
    return super.toString() + "[size:" + this.subscriptions.size() + "]";
  }

  public Subscription getSubscription(String consumerId) {
    return (Subscription)this.subscriptions.get(consumerId);
  }

  public void addSubscription(String consumerId, Subscription subscription) {
  }

  public Subscription removeSubscription(String consumerId) {
    return (Subscription)this.subscriptions.remove(consumerId);
  }

  public Iterator subscriptionIterator() {
    return this.subscriptions.values().iterator();
  }

  public Subscription makeSubscription(Dispatcher dispatcher, ConsumerInfo info, Filter filter) {
    Subscription subscription = createSubscription(dispatcher, info, filter);
    this.subscriptions.put(info.getConsumerId(), subscription);
    return subscription;
  }

  public void checkForDuplicateDurableSubscription(BrokerClient client, ConsumerInfo info) throws JMSException {
    for (Iterator iter = this.subscriptions.values().iterator(); iter.hasNext(); ) {
      Subscription subscription = (Subscription)iter.next();
      if (subscription.isSameDurableSubscription(info))
        throw new DuplicateDurableSubscriptionException(info);
    }
  }

  protected Subscription createSubscription(Dispatcher dispatcher, ConsumerInfo info, Filter filter)
  {
    return new SubscriptionImpl(dispatcher, info, filter);
  }
}